// import type Express from "express";
import type { RequestHandler } from "express";
import { resolve } from "path";
import { getModules, PROJECT_DIR } from "../node";
import { CreateExpressWsResult, ExpressAppSetupFunc } from "../node/network2";

/**
 * 自动导入backend/api
 * @example //backend/api/**.ts
 * import { Router } from "express";
 * let router = Router();
 * export const priority = 100; // priority: number, the bigger the priority, the earlier the router will be mounted. (default: 0)
 * export default router; // export anything, anything[] or Promise<anything> that goes into Express().use()
 */
export async function importApi({ app }: CreateExpressWsResult): Promise<void> {
  type AppUse = RequestHandler | Promise<RequestHandler>;
  let modules = getModules(resolve(PROJECT_DIR, "backend.js/api")).map(
    (e) => e.module.default as AppUse | AppUse[]
  );
  for (let mod0 of modules) {
    const _modRaw = await mod0;
    if (_modRaw instanceof Array) {
      for (let _modeFinal of _modRaw) {
        app.use(await _modeFinal);
      }
    } else {
      app.use(_modRaw);
    }
  }
}

export const autoImport: ExpressAppSetupFunc = async (server) => {
  await importApi(server);
};

export default autoImport;
